package com.chenyi.web.controller.system;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdminRole;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.core.page.TableDataInfo;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.common.utils.poi.ExcelUtil;
import com.chenyi.framework.web.service.AdminPermissionService;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.system.service.ISysAdminRoleService;
import com.chenyi.system.service.ISysAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin/role")
public class AdminRoleController extends BaseController
{
    @Autowired
    private ISysAdminRoleService roleService;

    @Autowired
    private AdminTokenService tokenService;
    
    @Autowired
    private AdminPermissionService permissionService;
    
    @Autowired
    private ISysAdminService userService;

    @PreAuthorize("@admin.hasPermi('system:role:list')")
    @GetMapping("/list")
    public ResponseEntity<TableDataInfo> list(SysAdminRole role)
    {
        startPage();
        List<SysAdminRole> list = roleService.selectAdminRoleList(role);
        return new ResponseEntity<>(getDataTable(list), HttpStatus.OK);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@admin.hasPermi('system:role:export')")
    @GetMapping("/export")
    public ResponseEntity<Object> export(SysAdminRole role)
    {
        List<SysAdminRole> list = roleService.selectAdminRoleList(role);
        ExcelUtil<SysAdminRole> util = new ExcelUtil<SysAdminRole>(SysAdminRole.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@admin.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public ResponseEntity<Object> getInfo(@PathVariable Long roleId)
    {
        return ResponseEntity.ok(roleService.selectAdminRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@admin.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseEntity<Object> add(@Validated @RequestBody SysAdminRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkAdminRoleNameUnique(role)))
        {
            throw new MessageException("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkAdminRoleKeyUnique(role)))
        {
            throw new MessageException("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(AdminUtils.getUsername());
        roleService.insertAdminRole(role);
        return new ResponseEntity<>(HttpStatus.CREATED);

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@admin.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> edit(@Validated @RequestBody SysAdminRole role)
    {
        roleService.checkAdminRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkAdminRoleNameUnique(role)))
        {
            throw new MessageException("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkAdminRoleKeyUnique(role)))
        {
            throw new MessageException("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(AdminUtils.getUsername());
        
        if (roleService.updateAdminRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getAdmin()) && !loginUser.getAdmin().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getAdmin()));
                loginUser.setAdmin(userService.selectAdminByUserName(loginUser.getAdmin().getUserName()));
                tokenService.setLoginAdmin(loginUser);
            }
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        throw new BadRequestException("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@admin.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public ResponseEntity<Object> dataScope(@RequestBody SysAdminRole role)
    {
        roleService.checkAdminRoleAllowed(role);
        return ResponseEntity.ok(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@admin.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(@RequestBody SysAdminRole role)
    {
        roleService.checkAdminRoleAllowed(role);
        role.setUpdateBy(AdminUtils.getUsername());
        return ResponseEntity.ok(roleService.updateAdminRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@admin.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public ResponseEntity<Object> remove(@PathVariable Long[] roleIds)
    {
        return ResponseEntity.ok(roleService.deleteAdminRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@admin.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public ResponseEntity<Object> optionselect()
    {
        return ResponseEntity.ok(roleService.selectAdminRoleAll());
    }
}
